// pages/mistake/mistake.js
const db = wx.cloud.database()
var app = getApp();
Page({
  data: {
    index: 0,
    openid:'',
    questionList: [],
    showModal: false,
  },
  swiper: function(e){
    var current = e.detail.current
    if(current == this.data.questionList.length){
      current = 0
    }
    this.setData({
      index: current
    })
  },
  
  jump: function(e){
    var current = e.currentTarget.dataset.current
    this.setData({
      index: current,
      showModal: false
    })
  },
  goredo: function(){
    wx.navigateTo({
      url: '../mistake/redo',
    })
  },
  onLoad: function(options){
    var that = this
    var openid = wx.getStorageSync('openid')
    if(!openid){
      wx.navigateTo({
        url: '../index/welcome',
      })
      return false
    }
    that.setData({
      openid
    })
  },
  onShow: function () {
    var that = this
    wx.showLoading({
      title: '加载中',
    })
    //查询userWrong表数据
    db.collection('userWrong').where({
      _openid: that.data.openid
    }).orderBy('type','desc').get({
      success: res => {
        var questionList = []
        res.data.forEach(function(item){
          item.question._id = item._id
          questionList.push(item.question)
        })
        console.log('questionList',questionList)
        that.setData({
          questionList: questionList
        })
        wx.hideLoading()
      },
      fail: err => {
        console.error('error', err)
      }
    })
  },
  delete: function(e){
    var id = e.currentTarget.dataset.id
    console.log('id',id)
    wx.showModal({
      title: '确认删除？',
      success: function (res) {
        if (res.cancel) {
        } else {
          db.collection('userWrong').doc(id).remove({
            success: res => {
              console.log(res)
              wx.redirectTo({
                url: '../mistake/mistake',
              })
            },
            fail: err => {
              console.error(err)
            }
          })
        }
      },
    })
  },
  showMask: function(){
    this.setData({
      showModal: true
    })
  },
  // 弹出层里面的弹窗
  hideMask: function () {
    this.setData({
      showModal: false
    })
  },
})
